package com.heima.article.service;

import com.alibaba.fastjson.JSONArray;
import com.heima.model.article.dtos.ArticleDto;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Freemarker组件类
 *
 * @Author mr.chen
 * @Date 2025/6/27 17:59
 */
@Component
public class FreemarkerService {

    @Autowired
    private Configuration configuration;

    /**
     * 生成模版
     *
     * @param dto
     * @return
     */
    public ByteArrayInputStream render(ArticleDto dto) {
        //1.2 将content字符串转为数组对象
        JSONArray content = JSONArray.parseArray(dto.getContent());
        try {
            //1. 获取模板对象
            Template template = configuration.getTemplate("article.ftl");
            //2. 准备模型数据
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("content", content);
            //3.准备输出流
            StringWriter stringWriter = new StringWriter();
            //把结果渲染到输出流中
            template.process(hashMap, stringWriter);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
            return byteArrayInputStream;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
